import React, { useState } from 'react';
import { Container, Form, Button, Card, Spinner, Alert } from 'react-bootstrap';
import axios from 'axios';

const KnowledgeQA = () => {
  const [inputText, setInputText] = useState('');
  const [qaResult, setQaResult] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const searchQA = async () => {
    try {
      setLoading(true);
      setError('');

      const response = await axios.post('http://127.0.0.1:5000/api/qa/search', { question: inputText });
      setQaResult(response.data);
    } catch (error) {
      console.error('搜索问题时发生错误:', error);
      setError('搜索问题时发生错误');
    } finally {
      setLoading(false);
    }
  };

  return (
    <Container className="mt-4">
      <h1 className="mb-4">知识问答</h1>

      <Card className="mb-4">
        <Card.Body>
          <Form>
            <Form.Group controlId="formInputText">
              <Form.Label>输入问题</Form.Label>
              <Form.Control
                as="textarea"
                rows={3}
                placeholder="输入要搜索的问题"
                value={inputText}
                onChange={(e) => setInputText(e.target.value)}
              />
            </Form.Group>
            <Button variant="primary" onClick={searchQA} disabled={loading}>
              {loading ? (
                <Spinner animation="border" size="sm" />
              ) : (
                '搜索'
              )}
            </Button>
          </Form>
        </Card.Body>
      </Card>

      {error && (
        <Alert variant="danger" className="mb-4">
          {error}
        </Alert>
      )}

      {qaResult && (
        <Card className="mb-4">
          <Card.Body>
            <Card.Title>匹配结果</Card.Title>
            <Card.Text><strong>问题：</strong>{qaResult.question}</Card.Text>
            <Card.Text><strong>答案：</strong>{qaResult.answer}</Card.Text>
          </Card.Body>
        </Card>
      )}
    </Container>
  );
};

export default KnowledgeQA;
